package lion.framework.core.task;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 任务定时器
 *
 * <pre>
 * time   2013 2013年7月16日 下午3:15:14
 * mail   hl_0074@sina.com
 * </pre>
 *
 * @author lion
 */
public class ScheduleTimerTask extends TimerTask {

	private Map<String, ISchedule> scheduleMap = new HashMap<>();
	private LinkedBlockingQueue<ISchedule> queue;

	public ScheduleTimerTask(List<ISchedule> schedules, LinkedBlockingQueue<ISchedule> queue) {

		for (ISchedule schedule : schedules) {
			scheduleMap.put(schedule.getId(), schedule);
		}

		this.queue = queue;
	}

	public void addSchedule(ISchedule schedule) {

		scheduleMap.put(schedule.getId(), schedule);
	}

	public int size() {

		return scheduleMap.size();
	}

	@Override
	public void run() {

		for (String key : scheduleMap.keySet()) {
			ISchedule schedule = scheduleMap.get(key);
			if (schedule.isTimeToRun() && scheduleMap.containsKey(schedule.getId())) {
				schedule.setStatus(TaskStatus.PENDING);
				schedule.sync();
				try {
					queue.put(schedule);
				} catch (InterruptedException e) {
				}
			}
		}
	}

	public boolean remove(String id) {

		return scheduleMap.remove(id) != null;
	}
}
